﻿using System;
using Apache.NMS;

namespace Reactor.Messaging.ServiceBus.Receiving
{
    public class SubscriptionReceiver : ReceiverBase
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="SubscriptionReceiver"/> class.
        /// </summary>
        /// <param name="nmsGateway">The JMS manager.</param>
        /// <param name="session">The session.</param>
        /// <param name="topic">The topic.</param>
        public SubscriptionReceiver(INmsGateway nmsGateway, ISession session, IMessagingChannel topic) : base(nmsGateway, session, topic)
        {
            if(!(topic is PubSubChannel)) throw new InvalidOperationException("Only SubscriptionTopics are used by SubscriptionCoordinators.");
            
            //var serviceBus = Context.ServiceLocator.GetInstance<IServiceBus>();
            //var serviceName = 
            //    (Context.CurrentReactorService == null || string.IsNullOrEmpty(Context.CurrentReactorService.Name))
            //    ? serviceBus.Configuration.CurrentEndpointInputChannel 
            //    : Context.CurrentReactorService.Name;
        }

        #region Implementation of IReceiver

        /// <summary>
        /// Starts this instance.
        /// </summary>
        public override void Start()
        {
            if (IsDisposed) throw new ObjectDisposedException("SubscriptionReceiver");

            var topic = Session.GetTopic(MessagingChannel.DestinationName);
            Consumer = Session.CreateConsumer(topic);
            Consumer.Listener += OnMessage;

            if (Log.IsInfoEnabled) Log.InfoFormat("SubscriptionReceiver started. Monitoring topic: {0}", MessagingChannel.DestinationName);
            IsRunning = true;
        }

        #endregion
    }
}
